"""
订单相关的公用方法
"""

import random
import datetime

from goods.models import SubGoodsOrder, Goods, GoodsOrder


def create_sub_order_id(user_id):
    """
    创建子订单订单号
    """

    return '2' + create_time_str(user_id)


def create_order_id(user_id):
    """
    创建子订单订单号
    """

    return '1' + create_time_str(user_id)


def create_time_str(user_id):
    """
    创建订单号公共部分
    """
    return str(datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(10, 99))) + str(user_id)


def create_order(user, pay_type):
    """
    创建主订单
    """
    order_id = create_order_id(user.id)
    order = GoodsOrder.objects.create(user=user, order_id=order_id, pay_type=pay_type)
    order.save()
    return order


def create_sub_order(order_id, goods_id, count, user_id):
    """
    创建子订单

    order_id: 父订单id
    goods_id: 商品id
    count: 商品数量
    """
    # 获取商品
    goods = Goods.objects.filter(id=goods_id).first()
    if not goods:
        return False
    # 创建订单号
    sub_order_id = create_sub_order_id(user_id)
    # 计算商品价格
    total_price = get_goods_total_price(goods.price, count)
    # 创建子订单
    sub_order = SubGoodsOrder.objects.create(order_id=order_id, goods=goods, count=count, show_price=goods.price,
                                             sub_order_id=sub_order_id, cur_total_price=total_price)
    sub_order.save()
    return sub_order


def get_goods_total_price(price, count):
    """
    计算商品价格
    """
    return price * count
